#-*- coding:utf-8 -*-

# The MIT License (MIT)
# 
# Copyright (c)  2014  Li Lin  <jzqlin@gmail.com>
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


"""
splitting module support the SQLAlchemy ORM style usage when a developer want to  
split a table into different tables and even in different databases. The splitted
tables can map to classes with same Column Attributes and inherited from 
SQLAlchmey declarative_base class.  

In this implementation, a table is only supported to split into 100 tables and 100 databases.
Developer can split their table into 100 tables by using TableSplitter only. And can split their 
table into 100 databases with 100 tables each, by using TableSplitter and DatabaseSplitter together.
"""

from sqlalchemy.ext.declarative import declarative_base
from hashlib import md5
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool
from sqlalchemy.orm import sessionmaker

class TableSplitter(object):
    """TableSplitter only supports a table splits into 100 tables.
    A new class is created for each splitted table.
    """
    
    
    def __init__(self, table_names, table_mapped_base_class, table_mapped_class_names):
        """Construct the TableSplitter object.
                
        :param table_names: A list of tables names, the list length MUST be 100
        :param table_mapped_base_class: A base class describing the table structure, in SQLAlchemy ORM style. 
        :param table_mapped_class_names: A list of classes names, TableSplitter will construct these
        classes, each class corresponds to a table.
        """
        self.sqlalchemy_base = declarative_base()    
        self.mapped_classes = []        
        for table_index in range(0, 100):
            # making new class
            newcls = type(table_mapped_class_names[table_index],
                           (table_mapped_base_class, self.sqlalchemy_base), 
                           dict(__tablename__ = table_names[table_index]))
        
            self.mapped_classes.append(newcls)            
        
            
    def get_class(self, split_id):
        """Get a SQLAlchemy ORM declarative class.
        
        :param split_id: An ID that as a key for the table splitting. Can be integer or string. If 
        it is a string, we make a hash and take the digit for splitting.
        :returns A SQLAlchemy ORM declarative class, developer can use it for the SQLAlchemy ORM's session
        operations.
        """
        if type(split_id) == int:
            index = split_id % 100
            return self.mapped_classes[index]
        elif type(split_id) == str:
            md5Hex = md5(split_id).hexdigest()
            index = int(md5Hex[0:6], 16) % 100
            return self.mapped_classes[index]  
    

class DatabaseSplitter(object):
    """DatabaseSplitter only supports a table splits in to 100 databases. A SQLAlchemy engine is created
    for each database. The engine will use NullPool as it's connection pool class, which means the
    engine will not maintain any connections to the databases.            
    """
    
    
    def __init__(self, database_urls):
        """Construct the DatabaseSplitter object.
        
        :param database_urls: A list of database URLs which can be used in SQLAlchemy create_engine() method.        
        """
        self.engines = []
        self.sessions = []
        for database_index in range(0, 100):
            engine = create_engine(database_urls[database_index], encoding='utf-8', poolclass=NullPool)
            self.engines.append(engine)
            Session = sessionmaker(engine)
            self.sessions.append(Session)
        
    
    def get_engine(self, split_id):
        """Get the SQLAlchemy engine, an engine specifies a database. 
        
        :param split_id: An ID that as a key for database splitting. Can be integer or string. If 
        it is a string, we make a hash and take the digit for splitting.
        """
        if type(split_id) == int:
            index = split_id * 0.01 % 100
            return self.engines[index]
        elif type(split_id) == str:
            md5Hex = md5(split_id).hexdigest()
            index = int(md5Hex[6:12], 16) % 100
            return self.engines[index]
        
        
    def get_session(self, split_id):
        """Get SQLAlchemy session.
        
        :param split_id: An ID that as a key for database splitting. Can be integer or string. If 
        it is a string, we make a hash and take the digit for splitting.
        """ 
        
        if type(split_id) == int:
            index = split_id * 0.01 % 100
            return self.sessions[index]
        elif type(split_id) == str:
            md5Hex = md5(split_id).hexdigest()
            index = int(md5Hex[6:12], 16) % 100
            return self.sessions[index]
        



